package com.jetpackframework.skin;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.LayoutInflaterCompat;

import com.jetpackframework.Reflector;

import java.lang.reflect.Field;
import java.util.Observable;
import java.util.Observer;

public class SkinActivityLifecycleCallBack implements Application.ActivityLifecycleCallbacks {
    private ArrayMap<Activity, Observer> mLayoutInflaterMap = new ArrayMap<>();
    private Observable observable;

    public SkinActivityLifecycleCallBack(Observable observable) {
        this.observable = observable;
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        LayoutInflater layoutInflater = activity.getLayoutInflater();
        try {
            //Android 布局加载器 使用 mFactorySet 标记是否设置过Factory
            //如设置过抛出一次
            //设置 mFactorySet 标签为false
            Reflector.with(layoutInflater).field("mFactorySet").set(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SkinLayoutInflaterFactory factory = new SkinLayoutInflaterFactory();
        LayoutInflaterCompat.setFactory2(layoutInflater,factory);
        mLayoutInflaterMap.put(activity,factory);
        observable.addObserver(factory);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        Observer remove = mLayoutInflaterMap.remove(activity);
        observable.deleteObserver(remove);
    }
}
